<?php

namespace StudyBuddy\Geo;

class Import {

    /**
     * Object of type MongoDB
     *
     * @see http://us3.php.net/mongodb
     *
     * @var object
     */
    protected $Mongo;

    /**
     * Location of "blocks" .csv file
     * File should be downloaded from Maxmind.com
     * website
     *
     * @var string
     */
    protected $blocksFile;
    protected $locationFile;
    protected $dir;

    /**
     *
     * Constructor
     * @param object $MongoDB Instance of php's MongoDB object
     * @param string $blocksFile full path to location of blocks .csv file
     * @param string $locationFile full path to location .csv File
     */
    public function __construct(\MongoDB $MongoDB, $blocksFile, $locationFile) {

        $this->Mongo = $MongoDB;
        $this->blocksFile = $blocksFile;
        $this->locationFile = $locationFile;
    }

    public function run() {
        $this->drop();
        $this->importBlocks();
        $this->importLocation();
    }

    protected function drop() {

        $this->Mongo->GEO_BLOCKS->drop();
        $this->Mongo->GEO_LOCATION->drop();

        return $this;
    }

    protected function importBlocks() {
        $handle = fopen($this->blocksFile, 'r');
        if (false === $handle) {
            throw new \Exception('Unable to read file: ' . $this->blocksFile);
        }

        $coll = $this->Mongo->GEO_BLOCKS;

        $row = 0;
        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
            $num = count($data);
            if ($num > 2 && is_numeric($data[0])) {
                $a = array(
                    's' => (float) $data[0],
                    'e' => (float) $data[1],
                    'l' => (int) $data[2]
                );

                $coll->insert($a);
            }

            $row+=1;
        }

        echo '<br>Imported ' . number_format($row) . ' rows to GEO_BLOCKS collection';

        $coll->ensureIndex(array('s' => 1));
        $coll->ensureIndex(array('e' => 1));
    }

    /**
     *
     * Create GEO_LOCATION collection
     * If one already exists it will be dropped first
     * and then recreated
     * @throws \Exception
     */
    protected function importLocation() {
        $handle = fopen($this->locationFile, 'r');
        if (false === $handle) {
            throw new \Exception('Unable to read file: ' . $this->locationFile);
        }

        $coll = $this->Mongo->GEO_LOCATION;
        $row = 0;
        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
            $num = count($data);
            if ($num > 6 && is_numeric($data[0])) {
                $a = array(
                    '_id' => (int) $data[0],
                    'cc' => \utf8_encode($data[1]),
                );

                /**
                 * Currently Region (state) only imported for US and Canada
                 */
                if (!empty($data[2]) && ('US' === $a['cc'] || 'CA' === $a['cc'])) {
                    $a['state'] = \utf8_encode($data[2]);
                }

                if (!empty($data[3])) {
                    $a['city'] = \utf8_encode($data[3]);
                }

                if (!empty($data[4])) {
                    $a['zip'] = \utf8_encode($data[4]);
                }

                if (!empty($data[5])) {
                    $a['lat'] = (double) $data[5];
                }

                if (!empty($data[6])) {
                    $a['lon'] = (double) $data[6];
                }

                $coll->insert($a);
                $row+=1;
            }
        }

        echo '<br>Imported ' . number_format($row) . ' rows to GEO_LOCATION collection';
    }

}
